<template>
  <div class="headteacher-edit-page">
    <el-card>
      <div class="edit-title">{{ isEdit ? '编辑' : '新增' }}班主任</div>
      <el-form :model="form" :rules="rules" ref="formRef" label-width="120px" class="headteacher-form">
        <el-form-item label="班主任：" prop="headTeacherId">
          <el-select v-model="form.headTeacherId" filterable placeholder="请选择班主任" style="width: 100%" @change="handleTeacherChange">
            <el-option v-for="teacher in teacherOptions" :key="teacher.id" :label="teacher.name" :value="teacher.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="负责年级：" prop="grade">
          <el-input v-model="form.grade" readonly placeholder="年级" style="width: 100%" />
        </el-form-item>
        <el-form-item label="负责班级：" prop="className">
          <el-input v-model="form.className" readonly placeholder="班级" style="width: 100%" />
        </el-form-item>
        <div class="form-actions">
          <el-button type="primary" @click="handleSubmit">确定</el-button>
          <el-button @click="goBack">取消</el-button>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { ElMessage } from 'element-plus';
import { getTeacherList, type TeacherData } from '@/api/teacher';
import { getClassList, getClassById, updateClass } from '@/api/class';

const router = useRouter();
const route = useRoute();
const formRef = ref();
const isEdit = computed(() => !!route.params.id);

const form = reactive({
  headTeacherId: '',
  headTeacherName: '',
  grade: '',
  classId: '',
  className: ''
});

const rules = {
  headTeacherId: [{ required: true, message: '请选择班主任', trigger: 'change' }],
  grade: [{ required: true, message: '请选择年级', trigger: 'change' }],
  classId: [{ required: true, message: '请选择班级', trigger: 'change' }]
};

const teacherOptions = ref<any[]>([]);
let allClassList: any[] = [];

const fetchTeachers = async () => {
  const res = await getTeacherList({ current: 1, size: 1000 });
  teacherOptions.value = res.data.records.map(t => ({
    ...t,
    id: String(t.id)
  }));
};

const fetchClasses = async () => {
  const res = await getClassList({ current: 1, size: 1000 });
  allClassList = res.data.records;
};

const fetchEditData = async () => {
  if (isEdit.value && route.params.id) {
    const res = await getClassById(Number(route.params.id));
    form.classId = String(res.data.id);
    form.grade = res.data.grade;
    form.className = res.data.className;
    form.headTeacherId = String(res.data.headTeacherId);
    
    // 找到对应的班主任信息
    const teacher = teacherOptions.value.find(t => t.id === form.headTeacherId);
    if (teacher) {
      form.headTeacherName = teacher.name;
    }
  }
};

const handleSubmit = () => {
  formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      // 更新班级的 headTeacherId
      const classInfo = allClassList.find(item => String(item.id) === form.classId);
      if (classInfo) {
        await updateClass({ ...classInfo, headTeacherId: form.headTeacherId });
        ElMessage.success(isEdit.value ? '编辑成功' : '新增成功');
        goBack();
      }
    }
  });
};

const goBack = () => {
  router.back();
};

const handleTeacherChange = (value: string) => {
  const teacher = teacherOptions.value.find(t => String(t.id) === value);
  if (teacher) {
    form.headTeacherName = teacher.name;
  }
};

onMounted(async () => {
  await fetchTeachers();
  await fetchClasses();
  await fetchEditData();
});
</script>

<style scoped>
.headteacher-edit-page {
  padding: 40px 24px;
}
.edit-title {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 24px;
}
.headteacher-form {
  background: #fafbfc;
  padding: 24px 16px 8px 16px;
  border-radius: 8px;
}
.form-actions {
  margin-top: 24px;
  text-align: left;
}
</style> 